package com.pinxixi.category.service;

import com.pinxixi.category.mapper.CategoryMapper;
import com.pinxixi.framework.domain.category.Category;
import com.pinxixi.framework.model.response.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    public ListResponseResult<Category> findListByPid(Long parentId) {
        List<Category> list = categoryMapper.findListByPid(parentId);
        QueryResult<Category> queryResult = new QueryResult<>();
        queryResult.setList(list);
        return new ListResponseResult<Category>(CommonCode.SUCCESS,queryResult);
    }

    public ResponseResult save(Category category) {
        if(category.getId() == null){
            categoryMapper.add(category);
        }else{
            categoryMapper.edit(category);
        }
        return new ResponseResult(CommonCode.SUCCESS);
    }

    public QueryResponseResult<Category> findOne(Long id) {
        Category category = categoryMapper.findOne(id);
        return new QueryResponseResult<Category>(CommonCode.SUCCESS,category);
    }

    public ResponseResult deleteAll(Long[] ids) {
        for(Long id : ids){
            this.deleteCategory(id);
        }
        return new ResponseResult(CommonCode.SUCCESS);
    }

    public void deleteCategory(Long id){
        //查询A1是否拥有子集
        List<Category> list = categoryMapper.findListByPid(id);
        if(list!= null && list.size() > 0){
            for(Category child : list){
                this.deleteCategory(child.getId());
            }
        }
        categoryMapper.delete(id);
    }

    public ListResponseResult<Category> findAll() {
        List<Category> list = categoryMapper.findAll();
        QueryResult<Category> queryResult = new QueryResult<>();
        queryResult.setList(list);
        return new ListResponseResult<Category>(CommonCode.SUCCESS,queryResult);
    }

    public QueryResponseResult<Category> findByName(String name) {
        Category category = categoryMapper.findByName(name);
        return new QueryResponseResult<>(CommonCode.SUCCESS,category);
    }

}
